<?php

namespace app\index\controller;

use app\BaseController;
use app\index\model\User as ModelUser;
use app\index\validate\User;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;

class Login extends BaseController
{
    public function index()
    {
        $this->logs('登录页面');

        $ref = request()->server('HTTP_REFERER');
        $regUri = 'http://' . request()->host() . '/index/register/index.html';
        if ($ref != $regUri) {
            Session::set('ref', $ref);
        }
        if (Session::has('user')) {
            return view('error/404', ['msg' => '无需重复登录']);
        }
        return view();
    }
    public function doLog()
    {
        $this->logs('登录');

        if (!config('system.switch.login')) return error('当前站点已关闭登录');
        if (Session::has('user'))  return error('无需重复登录');
        $param = input();
        try {
            validate(User::class)->scene('login')->check($param);
            if (!captcha_check($param['captcha']))  return error('验证码错误');
            $userData = Db::name('user')->where('username', $param['username'])->find();
            if (!$userData)  return error('用户不存在');
            $password =  md5(config('secure.secret_key') . $param['password']);
            if ($userData['password'] != $password) return error('账号或密码错误');
            if ($userData['status'] == 0) return error('该账户已被封禁');
            if ($userData['status'] == 2) return error('当前账户正在审核中，请耐心等待！');
            else {
                $data = [
                    'nickname' => $userData['nickname'],
                    'user_id' => $userData['id'],
                    'headIcon' => $userData['head_icon'],
                    'signature' => $userData['signature'],
                    'role' => $userData['role'],
                ];
                Session::set('user', $data);
                ModelUser::where('id', $userData['id'])->update(['login_time' => time()]);
                $ref = Session::has('ref')  ? Session::get('ref') : '/index/index/index';
                return success(['ref' => $ref, '登录成功']);
            }
            return error('登录失败');
        } catch (ValidateException  $e) {
            return error($e->getMessage());
        }
    }
    public function logout()
    {
        $this->logs('退出登录');
        if (Session::has('user')) {
            Session::set('user', null);
            Session::destroy();
            echo "<script>alert('退出成功');window.location.href='/index/'</script>";
        }
    }
}
